package org.bp.ioc.config;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.bp.ioc.utils.ReflectionUtils;

/**
 * 获取类与实例之间的映射
 */
public final class BeanHelper {
    private static final Map<Class<?>,Object> BEAN_MAP = new HashMap<>();

    static {
        Set<Class<?>> beanClassSet = ClassHelper.getBeanClassSet();
        for (Class<?> clazz : beanClassSet){
            BEAN_MAP.put(clazz, ReflectionUtils.newInstance(clazz));
        }
    }

    /**
     * 获取映射
     * @return
     */
    public static Map<Class<?>,Object> getBeanMap(){
        return BEAN_MAP;
    }

    /**
     * 获取实例
     * @param clazz
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
	public static <T> T getBean(Class<T> clazz){
        if(!BEAN_MAP.containsKey(clazz)){
            throw new RuntimeException(String.format("can not get bean by class : %s",clazz));
        }
        return (T) BEAN_MAP.get(clazz);
    }
}
